package com.fesine.batch.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.fesine.batch.model.UserPo;
import com.fesine.batch.service.UserService;
import com.fesine.commons.util.*;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description: 类描述
 * @author: Fesine
 * @createTime:2016/12/14 0:14
 * @update:修改内容
 * @author: Fesine
 * @updateTime:2016/12/14 0:14
 */
@Controller
@RequestMapping("/user")
public class UserController {
    private static final Logger logger = Logger.getLogger(UserController.class);
    @Autowired
    private UserService userService;

    public static SerializeConfig mapping = new SerializeConfig();

    /**
     * 分页查询用户信息
     *
     * @param req
     * @param response
     * @throws Exception
     */
    @RequestMapping("/listUser")
    public void listUser(HttpServletRequest req, HttpServletResponse response)
            throws Exception {
        int offset = Integer.parseInt(req.getParameter("start"));
        int pageSize = Integer.parseInt(req.getParameter("limit"));
        logger.info("分页查询用户信息，offset:[" + offset + "],pageSize:[" + pageSize + "]");
        int total = userService.findAll().size();
        JSONObject jsonObject = new JSONObject();
        List<UserPo> useList;
        if (offset>=0 && pageSize >0) {
            useList = userService.findAll(ConvertUtils.offsetToPageNum(offset,pageSize),pageSize);
        } else {
            useList = userService.findAll();
        }
        jsonObject.put("total", total);
        logger.info("------->查询总记录数[" + total + "]");
        String str = JSON.toJSONString(useList, mapping);
        JSONArray jsonArray = JSON.parseArray(str);
        jsonObject.put("rows", jsonArray);
        logger.info("--------->" + jsonObject);
        ResponseUtils.outPut(response, jsonObject);
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public void listAllProduct(HttpServletRequest req, HttpServletResponse response) {
        Map<String, Object> map = new HashMap<>();
        String username = req.getParameter("username");
        String captchaToken = ((String) req.getSession().getAttribute("captchaToken"))
                .toLowerCase();
        String checkCode = req.getParameter("checkCode").toLowerCase();
        logger.info("----->captchaToken:" + captchaToken + ",checkCode:" + checkCode);
        //不区分大小写
        if (!captchaToken.equals(checkCode.toLowerCase())) {
            map.put("success", false);
            map.put("msg", "验证码错误!");
        } else {
            if (userService.checkUsername(username)) {
                //用户名正确，再验证密码
                String password = req.getParameter("password");
                if (userService.login(username, CryptographyUtil.md5(password, "fesine"))) {
                    //创建用户session
                    HttpSession session = req.getSession();
                    session.setAttribute("username", username);
                    map.put("success", true);
                    map.put("msg", "验证成功!");
                } else {
                    map.put("success", false);
                    map.put("msg", "密码错误!");
                }
            } else {
                map.put("success", false);
                map.put("msg", "用户名不存在!");
            }
        }
        try {
            ResponseUtils.outPut(response, map);
        } catch (Exception e) {
            logger.error("", e);
        }
    }

    @RequestMapping("/logout")
    public void logout(HttpServletRequest req, HttpServletResponse response)
            throws Exception {
        req.getSession().invalidate();
        Map<String, Object> map = new HashMap<>();
        map.put("success", true);
        map.put("msg", "注销成功!");
        try {
            ResponseUtils.outPut(response, map);
        } catch (Exception e) {
            logger.error("", e);
        }
    }

    /**
     * 添加用户
     *
     * @param req
     * @param response
     * @throws Exception
     */
    @RequestMapping("/addUser")
    public void addUser(HttpServletRequest req, HttpServletResponse response)
            throws Exception {
        String username = req.getParameter("username");
        //如果用户名存在，返回true
        Map<String, Object> map = new HashMap<>();
        if (userService.checkUsername(username)) {
            map.put("success", false);
            map.put("msg", "用户名已经存在!");
        } else {
            String password = req.getParameter("password");
            UserPo user = new UserPo();
            user.setId(GenerateUUID.getUUId());
            user.setUsername(username);
            user.setPassword(CryptographyUtil.md5(password, "fesine"));
            int id = userService.register(user);
            if (id > 0) {
                map.put("success", true);
                map.put("msg", "用户添加成功!");
                logger.info("------->添加成功！");
            } else {
                map.put("success", false);
                map.put("msg", "用户添加失败!");
                logger.info("------->添加失败！");
            }
        }
        try {
            ResponseUtils.outPut(response, map);
        } catch (Exception e) {
            logger.error("", e);
        }
    }

    @RequestMapping("/updateUser")
    public void updateUser(HttpServletRequest req, HttpServletResponse response)
            throws Exception {
        Map<String, Object> map = new HashMap<>();
        String userId = req.getParameter("id");
        String password = req.getParameter("password");
        UserPo user = userService.findByUserId(userId);//根据id查询用户信息
        user.setPassword(CryptographyUtil.md5(password, "fesine"));
        userService.modify(user);
        map.put("success", true);
        map.put("msg", "用户更新成功!");
        logger.info("------->更新成功！");
        try {
            ResponseUtils.outPut(response, map);
        } catch (Exception e) {
            logger.error("", e);
        }
    }

    @RequestMapping("/deleteUser")
    public void deleteUser(HttpServletRequest req, HttpServletResponse response) throws
            IOException {
        Map<String, Object> map = new HashMap<>();
        String userIds = req.getParameter("userIds");
        userIds = MyStringUtils.replaceQuotes(userIds);
        String[] IdsArr = userIds.split(",");
        userService.delete(IdsArr);
        map.put("success", true);
        map.put("msg", "删除用户成功!");
        logger.info("------->删除用户成功！");
        try {
            ResponseUtils.outPut(response, map);
        } catch (Exception e) {
            logger.error("", e);
        }

    }

    @RequestMapping("/checkUsername")
    public void checkUsername(HttpServletRequest req, HttpServletResponse response)
            throws Exception {
        Map<String, Object> map = new HashMap<>();
        String username = req.getParameter("username");
        if (userService.checkUsername(username)) {
            map.put("success", false);
            map.put("msg", "用户名已经存在!");
        } else {
            map.put("success", true);
            map.put("msg", "用户名可以使用!");
        }
        try {
            ResponseUtils.outPut(response, map);
        } catch (Exception e) {
            logger.error("", e);
        }
    }
}
